package com.gxuwz.endrskyweather;

import android.os.Bundle;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.gxuwz.endrskyweather.adapter.AddCityListAdapter;
import com.gxuwz.endrskyweather.viewmodel.AddCityViewModel;

import java.util.ArrayList;

public class AddCityActivity extends AppCompatActivity {
    private AddCityViewModel viewModel;
    private AddCityListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_city);
        // 设置状态栏颜色
        getWindow().setStatusBarColor(getResources().getColor(R.color.black));
        // 隐藏ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        // 初始化搜索框和按钮
        EditText searchInput = findViewById(R.id.edt_search_text);
        ImageButton searchButton = findViewById(R.id.btn_search);
        // 初始化RecyclerView
        RecyclerView recyclerView = findViewById(R.id.city_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddCityListAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);
        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(AddCityViewModel.class);
        viewModel.getCities().observe(this, cities -> {
            adapter.updateData(cities);
        });
        // 搜索按钮点击事件
        searchButton.setOnClickListener(v -> {
            String query = searchInput.getText().toString().trim();
            if (!query.isEmpty()) {
                viewModel.searchCities(query);
            }
        });
        // 推荐城市点击事件：推荐城市控件ID表
        int[] recommendedCityIds = new int[]{
                // 广西14地级市 tv_城市名
                R.id.tv_nanning,
                R.id.tv_liuzhou,
                R.id.tv_guilin,
                R.id.tv_wuzhou,
                R.id.tv_beihai_great,
                R.id.tv_qinzhou,
                R.id.tv_guigang,
                R.id.tv_yulin,
                R.id.tv_baise,
                R.id.tv_hechi,
                R.id.tv_chongzuo,
                R.id.tv_fangchenggang,
                R.id.tv_laibin,
                R.id.tv_hezhou
        };
        // 为推荐城市控件设置点击事件
        for (int id : recommendedCityIds) {
            TextView cityView = findViewById(id);
            cityView.setOnClickListener(v -> {
                String cityName = ((TextView)v).getText().toString();
                searchInput.setText(cityName);
                viewModel.searchCities(cityName);
            });
        }

    }
}
